package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.im.HuanXinTemplate;
import com.itheima.domain.db.*;
import com.itheima.domain.mongo.UserLike;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.BlackListService;
import com.itheima.service.db.NotifiactionService;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FriendService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLikeService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.SettingVo;
import com.itheima.vo.UserLikeCountVo;
import com.itheima.vo.UserLikeVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SettingManager {

    @DubboReference
    QuestionService questionService;

    @DubboReference
    NotifiactionService notifiactionService;

    @DubboReference
    BlackListService blackListService;

    @DubboReference
    UserInfoService userInfoService;

    @DubboReference
    UserLikeService userLikeService;

    @DubboReference
    VisitorService visitorService;

    @DubboReference
    RecommendUserService recommendUserService;

    @DubboReference
    FriendService friendService;

    @Autowired
    HuanXinTemplate huanXinTemplate;

    public ResponseEntity findSetting() {
        //1.获取当前登陆者id和手机号
        User user = UserHolder.get();
        Long userId = user.getId();
        String mobile = user.getMobile();

        //2.调用service查询陌生人问题
        Question question = questionService.findByUserId(userId);

        //3.调用service查询通知设置
        Notification notification = notifiactionService.findByUserId(userId);

        //4.创建一个vo对象,封装返回的数据
        SettingVo vo = new SettingVo();
        vo.setId(userId);
        vo.setPhone(mobile);

        if (question != null) {
            vo.setStrangerQuestion(question.getStrangerQuestion());
        }

        if (notification != null) {
            vo.setLikeNotification(notification.getLikeNotification());
            vo.setPinglunNotification(notification.getPinglunNotification());
            vo.setGonggaoNotification(notification.getGonggaoNotification());
        }

        //5.返回vo
        return ResponseEntity.ok(vo);
    }

    public void setQuestion(String content) {
        //1.获取用户id
        Long userId = UserHolder.get().getId();

        //2.查询用户之前设置的问题
        Question question = questionService.findByUserId(userId);

        //3.判断问题是否为null
        if (question == null) {
            //4.若为空,就新增
            question = new Question();
            question.setUserId(userId);
            question.setStrangerQuestion(content);

            questionService.save(question);
        }else {
            //5.若不为空,就更新
            question.setStrangerQuestion(content);

            questionService.update(question);
        }
    }

    public void setNotification(Notification param) {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.查询之前用户的设置
        Notification notification = notifiactionService.findByUserId(userId);

        //3.判断设置对象是否为空
        if (notification == null) {
            //4.若为空则新增
            param.setUserId(userId);
            notifiactionService.save(param);
        }else {
            //5.若不为空则更新
            param.setId(notification.getId());
            notifiactionService.update(param);
        }
    }

    public ResponseEntity findBlackListByPage(Integer pageNum, Integer pageSize) {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.远程调用service,返回pageBeanVo
        PageBeanVo pageBeanVo = blackListService.findByPage(pageNum, pageSize, userId);

        //3.获取pageBeanVo中黑名单id集合
        List<BlackList> blackIdList = (List<BlackList>) pageBeanVo.getItems();

        //4.查询黑名单用户的userInfo,把每个userInfo放入一个新集合中UserInfoList
        //4.1声明UserInfoList
        List<UserInfo> userInfoList = new ArrayList<>();

        //4.2遍历blackIdList,获取黑名单用户id,通过id查询userInfo,将userInfo存入userInfoList
        //if (blackIdList!=null && blackIdList.size()>0) {   }
        if (CollUtil.isNotEmpty(blackIdList)) {
            blackIdList.forEach(blackList -> {
                UserInfo userInfo = userInfoService.findById(blackList.getBlackUserId());
                userInfoList.add(userInfo);
            });
        }

        //5.将UserInfoList设置给pageBeanVo
        pageBeanVo.setItems(userInfoList);

        //6.返回pageBeanVo
        return ResponseEntity.ok(pageBeanVo);
    }

    public void deleteBlackList(Long blackId) {
        //1.获取当前用户id
        //2.远程调用service完成删除操作
        blackListService.deleteByUserIdAndBlackId(UserHolder.get().getId(),blackId);
    }

    public ResponseEntity<UserLikeCountVo> query(){
        Long userId = UserHolder.get().getId();
        UserLikeCountVo userLikeCountVo=new UserLikeCountVo();
        userLikeCountVo.setEachLoveCount(userLikeService.queryEachLikeCount(userId));
        userLikeCountVo.setLoveCount(userLikeService.queryLikeCount(userId));
        userLikeCountVo.setFanCount(userLikeService.queryFanCount(userId));
        System.out.println(userLikeCountVo);
        return ResponseEntity.ok(userLikeCountVo);
    }

    public ResponseEntity<PageBeanVo> findqueryLikeList(Integer type, Integer page, Integer pagesize, String nickname){
        Long userid = UserHolder.get().getId();
        PageBeanVo pageBeanVo=new PageBeanVo();

        List<Long> userIds=new ArrayList<>();
        // type： 1 互相关注 2 我关注 3 粉丝 4 谁看过我
        switch (type){
            case 1:
                PageBeanVo vo1 = userLikeService.queryEachLikeList(userid, page, pagesize);
                List<UserLike> items1 = (List<UserLike>) vo1.getItems();
                for (UserLike item : items1) {
                    userIds.add(item.getUserId());
                }
                break;
            case 2:
                PageBeanVo vo2 = userLikeService.queryLikeList(userid, page, pagesize);
                List<UserLike> items2 = (List<UserLike>) vo2.getItems();
                for (UserLike item : items2) {
                    userIds.add(item.getLikeUserId());
                }
                break;
            case 3:
                PageBeanVo vo3=userLikeService.queryFanList(userid,page,pagesize);
                List<UserLike> items3 = (List<UserLike>) vo3.getItems();
                for (UserLike item : items3) {
                    userIds.add(item.getUserId());
                }
                break;
            case 4:
                PageBeanVo vo4 = visitorService.topVisitor(userid, page, pagesize);
                List<Visitor> items = (List<Visitor>) vo4.getItems();
                for (Visitor item : items) {
                    userIds.add(item.getVisitorUserId());
                }
                break;
            default:
                break;
        }

        if (CollUtil.isEmpty(userIds)){
            return ResponseEntity.ok(pageBeanVo);
        }

        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(userIds, nickname);

        List<UserLikeVo> userLikeVoList=new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UserLikeVo userLikeVo=new UserLikeVo();
            userLikeVo.setNickname(userInfo.getNickname());
            userLikeVo.setGender(userInfo.getGender());
            userLikeVo.setId(userInfo.getId());
            userLikeVo.setEducation(userInfo.getEducation());
            userLikeVo.setCity(userInfo.getCity());
            userLikeVo.setAvatar(userInfo.getAvatar());
            userLikeVo.setAge(userInfo.getAge());
            userLikeVo.setMarriage(userInfo.getMarriage());

            double score = recommendUserService.queryScore(userid, userInfo.getId());
            if (score==0){
                score= RandomUtil.randomDouble(50,90);
            }
            userLikeVo.setMatchRate((int) score);
            userLikeVoList.add(userLikeVo);
        }

        pageBeanVo.setItems(userLikeVoList);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity disLike(Long userId){
        Long id = UserHolder.get().getId();
        userLikeService.deleteUserLike(id,userId);
        return ResponseEntity.ok(null);
    }
    public ResponseEntity likeFan(Long userId){
        Long id = UserHolder.get().getId();
        userLikeService.saveUserLike(id,userId);
        Boolean like = userLikeService.isMutualLike(id, userId);
        if (like){
            friendService.addContact(id,userId);
        }else {
            huanXinTemplate.deleteContacts("HX:"+id,"HX:"+userId);
        }
        return ResponseEntity.ok(null);
    }
}
